using System;
using System.Collections;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Data.SQLite;
using LeisureCenter.Tools;

namespace LeisureCenter.LibraryBuilderThreads
{
    public class PlayingsLoggerThread : SleepingThread
    {
        private class Playing
        {
            public Playing(string fileName)
            {
                this.FileName = fileName;
                this.DateTime = DateTime.Now;
            }

            public string FileName;
            public DateTime DateTime;
        }

        private Queue<Playing> files = new Queue<Playing>();

        public void AddFile(string fileName)
        {
            lock (((ICollection)this.files).SyncRoot)
            {
                files.Enqueue(new Playing(fileName));
            }
            Wakeup();
        }

        protected override void DoWork()
        {
            while (!terminated)
            {
                Playing file = null;
                lock (((ICollection)this.files).SyncRoot)
                {
                    if (files.Count > 0)
                        file = files.Dequeue();
                    else
                        return;
                }
                CheckFile(file);
            }
        }

        private static void CheckFile(Playing playing)
        {
            SQLiteConnection connection = new SQLiteConnection(Properties.Settings.Default.ConnectionString);
            connection.Open();
            try
            {
                SQLiteCommand command = connection.CreateCommand();
                command.CommandText = string.Format(@"select id from Files where filename = '{0}'", SQLiteTools.EscapeSqlString(playing.FileName));
                long? id = (long?)command.ExecuteScalar();
                if (id == null)
                {
                    // the file isn't in the database so we add it
                    Program.LeisureCenterInstance.libraryManager.filesCheckerThread.AddFileToTable(new FileInfo(playing.FileName));
                    connection.Close();
                    connection.Open();
                    id = (long?)command.ExecuteScalar();
                }
                if (id != null)
                {
                    // add the playing
                    command = connection.CreateCommand();
                    command.CommandText = string.Format(@"insert into Playings (id, datetime) values ({0}, {1})", id, playing.DateTime.ToFileTime());
                    command.ExecuteNonQuery();
                }
            }
            finally
            {
                connection.Close();
            }
        }
    }
}
